package com.example.admin.controller.mianshiguan;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.example.admin.config.OSSUploadUtils;
import com.example.airobotsettings.dao.LoginDto;
import com.example.common.core.domain.R;
import org.springframework.beans.factory.annotation.Value;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.airobotinterviewrecord.util.Result;
import com.example.interviewer.domain.DigitalInterviewers;
import com.example.interviewer.service.IDigitalInterviewersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.data.redis.core.RedisTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
/**
 * 数字人面试官配置 Controller
 */
@RestController
@RequestMapping("/api/system/interviewers")
public class DigitalInterviewersController {
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Autowired
    private OSSUploadUtils ossUploadUtils;
    @Autowired
    private IDigitalInterviewersService digitalInterviewersService;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 查询数字人面试官配置列表
     */
    @GetMapping("/list")
    public Result<Page<DigitalInterviewers>> list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            DigitalInterviewers digitalInterviewers) {
        Page<DigitalInterviewers> digitalInterviewersPage = digitalInterviewersService.selectDigitalInterviewersList(digitalInterviewers, pageNum, pageSize);
        return Result.success(digitalInterviewersPage);
    }
    /**
     * 上传数字人面试官视频
     */
    @PostMapping("/uploadVideo")
    public Result<String> uploadVideo(@RequestParam("file") MultipartFile file, Integer id) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }

        // 获取文件扩展名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();

        // 限制支持的视频格式
        if (!"mp4".equals(fileExtension) && !"webm".equals(fileExtension)) {
            return Result.error("只支持MP4和WEBM格式的文件");
        }

        // 生成唯一的文件名
        String newFileName = UUID.randomUUID().toString() + "." + fileExtension;
        String objectName = "uploads/videos/" + newFileName;

        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 上传文件到阿里云OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);

            // 上传并设置为公开读取权限
            ossClient.putObject(putObjectRequest);
            ossClient.setObjectAcl(bucketName, objectName, CannedAccessControlList.PublicRead);

            // 生成公共访问URL
            String videoUrl = String.format("https://%s.%s/%s", bucketName, endpoint, objectName);

            // 关闭OSS客户端
            ossClient.shutdown();

            // 更新数字面试官的视频路径
            DigitalInterviewers interviewers = new DigitalInterviewers();
            interviewers.setId(id.longValue());
            interviewers.setVideoPath(videoUrl);
            digitalInterviewersService.updateDigitalInterviewers(interviewers);

            // 返回成功响应
            return Result.success("文件上传成功", videoUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败: " + e.getMessage());
        } finally {
            // 确保OSS客户端被正确关闭
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 获取视频URL
     */
    @GetMapping("/getVideoUrl/{id}")
    public Result<String> getVideoUrl(@PathVariable("id") Long id) {
        try {
            DigitalInterviewers interviewer = digitalInterviewersService.selectDigitalInterviewersById(id);
            if (interviewer == null || interviewer.getVideoPath() == null) {
                return Result.error("视频不存在");
            }

            // 如果URL已经过期，重新生成
            if (interviewer.getVideoPath().contains("Expires=")) {
                String objectName = interviewer.getVideoPath().substring(interviewer.getVideoPath().indexOf("uploads/"));
                String videoUrl = String.format("https://%s.%s/%s", bucketName, endpoint, objectName);
                
                // 更新数据库中的URL
                interviewer.setVideoPath(videoUrl);
                digitalInterviewersService.updateDigitalInterviewers(interviewer);
                
                return Result.success(videoUrl);
            }

            return Result.success(interviewer.getVideoPath());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取视频URL失败: " + e.getMessage());
        }
    }

    /**
     * 上传数字人面试官头像
     */
    @PostMapping("/uploadAvatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file, Integer id) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }

        // 获取文件扩展名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();

        // 限制支持的图片格式
        if (!"jpg".equals(fileExtension) && !"jpeg".equals(fileExtension) && !"png".equals(fileExtension)) {
            return Result.error("只支持JPG、JPEG和PNG格式的图片");
        }

        // 生成唯一的文件名
        String newFileName = UUID.randomUUID().toString() + "." + fileExtension;
        String objectName = "uploads/avatars/" + newFileName;

        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 上传文件到阿里云OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);

            // 上传并设置为公开读取权限
            ossClient.putObject(putObjectRequest);
            ossClient.setObjectAcl(bucketName, objectName, CannedAccessControlList.PublicRead);

            // 生成公共访问URL
            String avatarUrl = String.format("https://%s.%s/%s", bucketName, endpoint, objectName);

            // 关闭OSS客户端
            ossClient.shutdown();

            // 更新数字面试官的头像路径
            DigitalInterviewers interviewers = new DigitalInterviewers();
            interviewers.setId(id.longValue());
            interviewers.setAvatar(avatarUrl);
            digitalInterviewersService.updateDigitalInterviewers(interviewers);

            // 返回成功响应
            return Result.success("头像上传成功", avatarUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("头像上传失败: " + e.getMessage());
        } finally {
            // 确保OSS客户端被正确关闭
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 获取头像URL
     */
    @GetMapping("/getAvatarUrl/{id}")
    public Result<String> getAvatarUrl(@PathVariable("id") Long id) {
        try {
            DigitalInterviewers interviewer = digitalInterviewersService.selectDigitalInterviewersById(id);
            if (interviewer == null || interviewer.getAvatarPath() == null) {
                return Result.error("头像不存在");
            }

            // 如果URL已经过期，重新生成
            if (interviewer.getAvatarPath().contains("Expires=")) {
                String objectName = interviewer.getAvatarPath().substring(interviewer.getAvatarPath().indexOf("uploads/"));
                String avatarUrl = String.format("https://%s.%s/%s", bucketName, endpoint, objectName);
                
                // 更新数据库中的URL
                interviewer.setAvatarPath(avatarUrl);
                digitalInterviewersService.updateDigitalInterviewers(interviewer);
                
                return Result.success(avatarUrl);
            }

            return Result.success(interviewer.getAvatarPath());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取头像URL失败: " + e.getMessage());
        }
    }

    /**
     * 导出数字人面试官配置列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(defaultValue = "1") int pageNum,
                       @RequestParam(defaultValue = "10") int pageSize,
                       DigitalInterviewers digitalInterviewers) {
        try {
//             如果你要导出当前分页的数据（分页导出）
             List<DigitalInterviewers> list = digitalInterviewersService
                     .selectDigitalInterviewersList(digitalInterviewers, pageNum, pageSize).getRecords();

            // ... existing code ...
            // 如果你要导出全部数据（不分页导出）：
            int largePageSize = Integer.MAX_VALUE;
            List<DigitalInterviewers> allList = digitalInterviewersService
                    .selectDigitalInterviewersList(digitalInterviewers, 1, largePageSize).getRecords();

            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("数字人面试官配置数据", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 写 Excel
            EasyExcel.write(response.getOutputStream(), DigitalInterviewers.class)
                    .sheet("数字人面试官")
                    .doWrite(list);

        } catch (IOException e) {
            throw new RuntimeException("导出 Excel 失败", e);
        }
    }


    /**
     * 获取数字人面试官配置详细信息
     */
    @GetMapping(value = "/{id}")
    public DigitalInterviewers getInfo(@PathVariable("id") Long id) {
        return digitalInterviewersService.selectDigitalInterviewersById(id);
    }

    /**
     * 新增数字人面试官配置
     */
    @PostMapping
    public Result<Integer> add(@RequestBody DigitalInterviewers digitalInterviewers) {
        // 检查名称是否已存在
        DigitalInterviewers query = new DigitalInterviewers();
        query.setName(digitalInterviewers.getName());
        List<DigitalInterviewers> existingList = digitalInterviewersService.selectDigitalInterviewersList(query, 1, 1).getRecords();
        if (!existingList.isEmpty()) {
            return Result.error("该面试官名称已被使用");
        }
        return Result.success(digitalInterviewersService.insertDigitalInterviewers(digitalInterviewers));
    }

    /**
     * 修改数字人面试官配置
     */
    @PutMapping
    public Result<Integer> edit(@RequestBody DigitalInterviewers digitalInterviewers) {
        // 检查名称是否已被其他记录使用
        DigitalInterviewers query = new DigitalInterviewers();
        query.setName(digitalInterviewers.getName());
        List<DigitalInterviewers> existingList = digitalInterviewersService.selectDigitalInterviewersList(query, 1, 1).getRecords();
        if (!existingList.isEmpty() && !existingList.get(0).getId().equals(digitalInterviewers.getId())) {
            return Result.error("该面试官名称已被使用");
        }
        return Result.success(digitalInterviewersService.updateDigitalInterviewers(digitalInterviewers));
    }

    /**
     * 删除数字人面试官配置
     */
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable Long[] ids) {
        return Result.success(digitalInterviewersService.deleteDigitalInterviewersByIds(ids));
    }
}
